#include <QPainter>
#include <QStandardItemModel>

#include "defs.h"
#include "rentgendelegate.h"
#include "manager.h"

RentgenDelegate::RentgenDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

RentgenDelegate::~RentgenDelegate()
{
}

void RentgenDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (option.state & QStyle::State_Selected)
    {
        QRect all = option.rect.adjusted(2, 2, -2, -2);
        painter->setBrush(QBrush( Qt::lightGray ));
        painter->drawRoundedRect(all, 10.0, 10.0);
        painter->setBrush(QBrush());
    }

    if (App->pacient()->rentgensCount()==0)
        return;

    const int curRow = index.row();
    const QStandardItemModel *rent = App->pacient()->rentgens();

    QString title ( rent->data(rent->index(curRow, RentName)).toString() );
    QString src ( rent->data(rent->index(curRow, RentSrc)).toString() );

    QRect allRect = option.rect.adjusted(2, 2, -2, -2);
    painter->drawRoundedRect(allRect, 10.0, 10.0);

    QRect iconRect = allRect.adjusted(10, 5, 0, 0);
    iconRect.setSize(QSize(65, 65));
    QRect titleRect = iconRect.adjusted(iconRect.width()+12, 0, 0, 0);
    titleRect.setSize(QSize(allRect.width()-titleRect.x()-10, allRect.height()/3));
    QFont curFont("Helvetica", 14, QFont::Bold);
    painter->setFont(curFont);
    painter->drawText(titleRect, title, Qt::AlignLeft | Qt::AlignVCenter);
    curFont = QFont("Helvetica", 8);
    curFont.setItalic(true);
    QRect srcRect = titleRect.adjusted(0,titleRect.height()+4, 0, titleRect.height());
    painter->setFont(curFont);
    painter->drawText(srcRect, src, Qt::AlignLeft | Qt::AlignVCenter);

    if ( !App->isIconLoaded(src) )
    {
        App->freeIcon(src);
        App->loadIcon(src);
    }

    QPixmap *icon = App->iconAt(src);
    painter->drawPixmap(iconRect.x(), iconRect.y(),
                        icon->scaled(iconRect.width(), iconRect.height(), Qt::KeepAspectRatio));

}

QSize RentgenDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option); Q_UNUSED(index);
    return QSize(50, 80);
}
